<?php
namespace hangpu8\hpcms\Utils\Builder;

use FormBuilder\Driver\CustomComponent;
use FormBuilder\Factory\Elm;
use FormBuilder\Form;

class FormService extends Form
{
    private $builder;
    private $data;

    /**
     * 构造函数
     *
     * @param string $url
     * @param array $rule
     * @param array $config
     */
    public function __construct(string $url = '',array $rule = [],array $config = [])
    {
        if (empty($url))
        {
            $request = request();
            $query = $request->request()['s'];
            $query = substr($query,1);
            $url = "{$query}";
        }
        $form = Form::elm($url,$rule,$config);
        $this->builder = $form;
    }

    /**
     * 添加表单行
     *
     * @param string $field 组件字段
     * @param string $type 组件类型
     * @param string $title 组件标题
     * @param [type] $value 组件默认值
     * @param array $extend 扩展数据
     * @return $this
     */
    public function addRow(string $field,string $type,string $title,$value = '', array $extend = [])
    {
        if ($type == 'custom') {
            // 创建自定义组件
            $component = new CustomComponent($extend['type']);
            // 设置字段，默认数据等
            $component
            ->field($field)
            ->title($title)
            ->value($value);
            // 设置组件属性
            if (isset($extend['extra']) && $extend['extra']) {
                $component->props($extend['extra']);
            }
        }else{
            $component = Elm::$type($field,$title,$value);
            if ($extend)
            {
                foreach ($extend as $componentType => $componentTypeValue)
                {
                    $component->$componentType($componentTypeValue);
                }
            }
        }
        $this->builder->append($component);
        return $this;
    }

    /**
     * 设置行数据
     *
     * @param array $data 表单数据
     * @return $this
     */
    public function setFormData(array $data)
    {
        $this->builder->formData($data);
        return $this;
    }

    /**
     * 设置请求方式
     *
     * @param [type] $method
     * @return $this
     */
    public function setMethod($method = 'GET')
    {
        $this->builder->setMethod(strtoupper($method));
        return $this;
    }

    /**
     * 快速生成表单
     *
     * @return array
     */
    public function create()
    {
        $apiUrl = $this->builder->getAction();
        $method = $this->builder->getMethod();
        $this->data['config']['api'] = str_replace('api/','',$apiUrl);
        $this->data['config']['method'] = $method;
        $this->data['formRule'] = $this->builder->formRule();
        return $this->data;
    }

    /**
     * 获取builder生成类对象
     *
     * @return $this
     */
    public function getBuilder()
    {
        return $this->builder;
    }
}